import { Image, View } from "@tarojs/components";
import useSetState from "@/utils/useSetState";
import classNames from "classnames";
import classes from "./index.module.less";

type Props = {
  image: { url: string; width: number };
  columns: [number, number];
  onLoad?: () => void;
};
type PositonCss = { top?: number; left?: number; right?: number };
const ImageBox: React.FC<Props> = ({ image, columns, onLoad = () => {} }) => {
  const [{ position, realHeight }, setState] = useSetState({
    position: { left: 12, top: 12 } as PositonCss,
    realHeight: 0,
  });
  return (
    <View
      key={image.url}
      className={classNames(classes.item, realHeight && classes.show)}
      style={{ ...position }}
    >
      <Image
        style={{ width: image.width, height: realHeight }}
        lazyLoad
        mode="aspectFill"
        onLoad={(e) => {
          const height = Number(e.detail.height);
          const width = Number(e.detail.width);
          const realHeight = image.width * (height / width);

          let position: PositonCss = {};
          if (columns[0] > columns[1]) {
            position = {
              top: columns[1],
              right: 12,
            };
            columns[1] += realHeight + 10;
          } else {
            position = {
              top: columns[0],
              left: 12,
            };
            columns[0] += realHeight + 10;
          }
          setState({ position, realHeight });
          onLoad();
        }}
        className={classes.img}
        src={image.url}
      />
      <View className={classes.text}>西安千古情旅游海报</View>
    </View>
  );
};

export default ImageBox;
